package egs.games;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Console;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

import egs.games.CheckersGame;
import egs.games.Move;
import egs.games.SquareState;
import egs.packets.EndGamePacket;

public class CheckersClient 
{
	private static BufferedWriter allMovesLog;
	private static BufferedWriter validMovesLog;
	private static CheckersClient client1 = null;
	private static CheckersClient client2 = null;
	
	private Queue<String> replayMoveQueue = new LinkedList<String>();
	private int replayMoveDelay;
	
	private CheckersGame checkers;
	private int player = -1;
	private String[] lastMove = null;

	public CheckersClient(CheckersGame checkers2, int player2) 
	{
		checkers = checkers2;
		player = player2;
	}

	public static void main(String[] args) throws IOException, InterruptedException
	{
		initLogs();
		printWelcome();
		try
		{			
			CheckersGame checkers1 = new CheckersGame(CheckersGame.getInitGameStateP2Top());
			CheckersGame checkers2 = new CheckersGame(CheckersGame.getInitGameStateP2Top());
			
			client1 = new CheckersClient(checkers1, 1);
			client2 = new CheckersClient(checkers2, 2);
			
			if (args.length != 0)
				processArgs(args);
			
			boolean p1Turn = false;
			int myPlayerNum = 1;
			int oppPlayerNum = 2;
			int gameEndState = -1; 
			
			while((gameEndState = client1.getGame().getGameOver()) == CheckersGame.CONTINUE_GAME)
			{
				CheckersClient currentClient = null;
				CheckersClient otherClient = null;
				if (p1Turn)
				{
					currentClient = client1;
					otherClient = client2;
				}
				else
				{
					currentClient = client2;
					otherClient = client1;
				}
				
				currentClient.updateBoardDisplay();
				
				System.out.println();
				System.out.println(p1Turn ? "Player 1 Turn: " : "Player 2 Turn: ");
				
				String input = currentClient.getMove();
				
				if(input.equalsIgnoreCase("exit") || input.equalsIgnoreCase("quit"))
					break;
				
				boolean validMove = currentClient.executeMove(input);
				
				if (validMove)
				{
					otherClient.acceptMove(currentClient.getGame().getBoardState(), p1Turn ? 1 : 2);
					p1Turn = !p1Turn;
				}
			}
			
			printResult(gameEndState);
		}
		finally
		{
			closeLogs();
		}
	}
	
	public CheckersGame getGame()
	{
		return checkers;
	}
	
	public void updateBoardDisplay() 
	{
		System.out.println();
		System.out.print(CheckersGame.printBoardState(checkers.getBoardState()));		
	}

	public boolean executeMove(String input) throws IOException 
	{
		int[][] board = checkers.getBoardState();
		String[] moveDef = null;
		if (input.equalsIgnoreCase("last") && lastMove != null)
			moveDef = lastMove ;
		else
		{
			moveDef = input.split(" ");
			lastMove = moveDef;
		}
		
		if (moveDef.length != 4)
		{
			System.err.println("Incorrect move format, must be 4 integers");
			return false;
		}
		
		short fromRow = Short.parseShort(moveDef[0]);
		short fromCol = Short.parseShort(moveDef[1]);
		
		short toRow = Short.parseShort(moveDef[2]);
		short toCol = Short.parseShort(moveDef[3]);
		
		boolean validMove = isMoveInBounds(fromRow, fromCol, toRow, toCol);
		
		Move move = null;
		if (validMove)
		{
			int piece = board[fromRow][fromCol];
			move = new Move();
			move.setMoveStart(new SquareState(fromRow, fromCol, piece));
			move.setMoveEnd(new SquareState(toRow, toCol, piece));
		}
		
		if (validMove)
			validMove = capturePieces(board, move);
		
		if (validMove)
			validMove = makeMove(board, move);
		
		if (validMove)
		{
			int result = checkers.verifyMove(board, player);
			validMove = result == 0;
			
			if (!validMove)
				System.out.println("Invalid move.  Error code: " + result);
		}
			 
		
		if (validMove)
		{
			checkers.updateState(board);
			logValidMove(input);
		}
		
		return validMove;
	}

	public String getMove() throws IOException, InterruptedException
	{
		System.out.println("Player " + player  + ", please enter move (fromRow fromCol toRow toCol) :");
		String input = "";
		if ((input = replayMoveQueue.poll()) != null)
		{
			Thread.sleep(replayMoveDelay);
			System.out.println("Replaying move: " + input);
		}
		else
		{
			BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
			input = reader.readLine();
		}
		logMove(input);
		
		return input;
	}

	private boolean isMoveInBounds(short fromRow, short fromCol, short toRow, short toCol) 
	{
		if (fromRow < 0 || fromCol < 0 || fromRow >= checkers.getHeight() || fromCol >= checkers.getWidth())
		{
			System.err.println("Move is out of bounds.");
			return false;
		}
		
		if (toRow < 0 || toCol < 0 || 
			toRow >= checkers.getHeight() || toCol >= checkers.getWidth())
		{
			System.err.println("Move is out of bounds.");
			return false;
		}

		
		return true;
	}

	private static void printWelcome() 
	{
		System.out.println();
		System.out.println("Welcome to the EGS Checkers Implementation.");
		System.out.println("Use the -r [file] [delayInMs] option to replay log files");
		System.out.println("Set window to 24 lines for optimal viewing");
		System.out.println();
		System.out.println("Enter moves in the format:");
		System.out.println("from_row from_col to_row to_col");
		System.out.println();
		System.out.println("All jumps for a move will be processed at once,\nso be sure to enter your piece's final destination when jumping.");
		System.out.println();
		System.out.println("Type \"last\" to try and repeat a move.");
		System.out.println("Type \"exit\" to leave the game.");
		System.out.println();
	}

	public static void printResult(int gameEndState) 
	{
		if (gameEndState == CheckersGame.CONTINUE_GAME)
			System.out.println("Exited before game concluded.");
		else if (gameEndState == CheckersGame.P2_WIN)
			System.out.println("You lost.");
		else if (gameEndState == CheckersGame.P1_WIN)
			System.out.println("You won!");
		else if (gameEndState == CheckersGame.TIE)
			System.out.println("Tie game.");
	}

	private static void processArgs(String[] args) throws IOException 
	{
		for (int i=0; i < args.length; i ++)
		{
			String arg = args[i];
			if (arg.equalsIgnoreCase("-r") && args.length > i+2)
			{
				String replayFile = args[i+1];
				int delay = Integer.parseInt(args[i+2]);
				queueReplayMovesBothClients(replayFile, delay);	
			}
		}
		
	}
	private static void queueReplayMovesBothClients(String replayFile, int delay) throws IOException
	{
		boolean isPlayer1Line = false;
		
		BufferedReader reader = new BufferedReader(new FileReader(new File(replayFile)));
		String line = null;
		while ((line = reader.readLine()) != null)
		{
			if (isPlayer1Line)
				client1.replayMoveQueue.offer(line);
			else
				client2.replayMoveQueue.offer(line);
			
			isPlayer1Line = !isPlayer1Line;
		}
		
		client1.replayMoveDelay = delay;
		client2.replayMoveDelay = delay;
	}
	
	public void queueReplayMoves(String replayFile, int delay) throws IOException 
	{
		BufferedReader reader = new BufferedReader(new FileReader(new File(replayFile)));
		String line = null;
		while ((line = reader.readLine()) != null)
			replayMoveQueue.offer(line);
		
		replayMoveDelay = delay;
	}

	private static void closeLogs() throws IOException 
	{
		allMovesLog.close();
		validMovesLog.close();
	}

	public static void initLogs() throws IOException 
	{
		allMovesLog = new BufferedWriter(new FileWriter(new File("all_moves_" + System.currentTimeMillis() + ".txt")));
		validMovesLog = new BufferedWriter(new FileWriter(new File("valid_moves_" + System.currentTimeMillis() + ".txt")));
	}

	private boolean capturePieces(int[][] board, Move move) 
	{
		// If the piece moves one row, it is by definition not a jump.  A jump may move 0, 2, 4, etc rows but only multiples of two
		if (Math.abs(move.getMoveStart().row() - move.getMoveEnd().row()) == 1)
			return true;
		
		ArrayList<Move> nextJumps = checkers.getNextJumps(move.getMoveStart(), new ArrayList<SquareState>());
		for (Move jump: nextJumps )
		{
			ArrayList<SquareState> capdPieces = findCapturedPiecesFromMove(board, move, jump);
			if (capdPieces != null)
			{
				move.getCapturedPieces().addAll(capdPieces);
				return true;
			}
		}
		
		System.err.println("Invalid jump.");
		return false;
	}

	private ArrayList<SquareState> findCapturedPiecesFromMove(int[][] board, Move move, Move jump) 
	{
		// If this jump lands us on the correct square
		if (jump.getMoveEnd().row() == move.getMoveEnd().row() &&
			jump.getMoveEnd().col() == move.getMoveEnd().col())
		{
			// Set the move end state piece, in case the jump involved turning a piece into a king
			move.setMoveEnd(new SquareState(jump.getMoveEnd().row(), jump.getMoveEnd().col(), 
					jump.getMoveEnd().piece()));
			
			return jump.getCapturedPieces();
		}
		// If it does not, search for more jumps that might get us to the right square
		else
		{			
			ArrayList<Move> nextJumps = checkers.getNextJumps(jump.getMoveEnd(), jump.getCapturedPieces());
			for (Move nextJump : nextJumps )
			{
				ArrayList<SquareState> capdPieces = findCapturedPiecesFromMove(board, move, nextJump);
				if (capdPieces != null)
					return capdPieces;
			}
		}
		
		return null;
	}

	public boolean makeMove(int[][] board, Move move) 
	{		
		board[move.getMoveStart().row()][move.getMoveStart().col()] = CheckersGame.EMPTY;
		
		int moveEndPiece = move.getMoveEnd().piece();
		if (checkers.needsKingMe(move.getMoveEnd().row(), move.getMoveEnd().piece()))
			moveEndPiece = checkers.kingMe(move.getMoveEnd().piece());
			
		board[move.getMoveEnd().row()][move.getMoveEnd().col()] = moveEndPiece;
		
		for (SquareState capdPiece : move.getCapturedPieces())
		{
			board[capdPiece.row()][capdPiece.col()] = CheckersGame.EMPTY;
		}
		
		return true;
	}
	
	public void logMove(String log) throws IOException 
	{
		allMovesLog.write(log + "\n");
		allMovesLog.flush();
	}

	private void logValidMove(String log) throws IOException 
	{
		validMovesLog.write(log + "\n");
		validMovesLog.flush();
	}

	public int acceptMove(int[][] board, int player) 
	{
		 return this.getGame().makeMove(CheckersGame.copyBoard(board), player);
	}
}
